<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PAPER</title>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />


<style type="text/css">

body {
	background-image: url('../../images/paper-bg.jpg');	
	background-repeat: repeat-x;
	background-attachment: fixed;
}

table,td,th {
	border: 0px;
	border-spacing: 0px;
}

#sadari { margin-left: 170px; margin-top: 40px; }

.ch {  	
    position: absolute;    
    left: 50px;
    width: 90px;
    height: 90px;
    margin: 5px;
}

.boom {
	position: absolute;
	display: none;
	margin-left: 15px;
	margin-top: 10px;
}

.label_name { 
  	-webkit-box-shadow: 0 0 5px #aaa; 
  	box-shadow: 0 0 5px #aaa; 
  	padding: 8px;
	z-index: 9999;
	position: absolute;
    top: -10px;
   	left: 70px;
   	background-color: #c0c0c0;
   	opacity: 0.6;
   	color: #fff;
   	border-radius: 25px;
   	font-size: small;
   	font-weight: bold;   	
   	display:none;   	
}

.input_goal{
	width: 90px;
	text-align: center;
}
.cell {
	border: 0px;
	padding: 0px;
	width: 100px;
	height: 60px;
	background-image: url("../../images/00.png");
	background-position: center;
}

</style>

</head>
<body>

<div>

	<h1>${paper.name }</h1>
	(${fn:length(paper.users) }/${paper.maxUser })<br/>
	
	<c:if test="${paper.soloMode }">
	<span>혼자 모든걸 처리하는 모드!!</span><br/>
	</c:if>
	<c:if test="${paper.oneGoal }">
	<span>결과는 단 하나뿐인 모드!!</span><br/>
	</c:if>
	 
	<div id="paper_status" style="height: 50px;"></div>
	<p>
		위대한 ${sadari_user.alias }, ${sadari_user.name } 님
		<c:if test="${isLeader }"> - 리더</c:if>
	</p>	
</div>

<div>
	<button id="btn_draw" class="btn_leader">새로 그리기</button>
	<button id="btn_accept" class="btn_leader">결정!!</button>
	<button id="btn_go">GO!</button>
	<button id="btn_back">돌아가기</button>
</div>


<div>

<table id="sadari"></table>

</div>

<div id="dialog_input_goals" title="결과를 입력하세요!">
	<ol>
	<c:forEach var="i" begin="0" end="${paper.maxUser - 1 }">
	<li><input type="text" id="dialog_input_goal_${i }"></li>
	</c:forEach>
	</ol>
	<input type="checkbox" id="dialog_input_goal_random"><label for="dialog_input_goal_random">순서 섞기</label>	
</div>

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<script type="text/javascript">

var status_text = ["준비 중", "오픈", "사다리 확정", "종료"];

//세로 길이
var line = ${paper.line };

// 참가 인원
var num = ${paper.maxUser };

// 사다리 모델
var model = [];

// timer id
var timer = [];

var isLeader = ${isLeader };

var isSoloMode = ${paper.soloMode};
var isOneGoal = ${paper.oneGoal};
var realGoalNumber = ${paper.realGoalNumber };
var boomLine = ${paper.boomLine };

var status = ${paper.status };

var paperId = "${paper.id}";

$().ready(function(){
	
	//결과 입력 dialog
	$("#dialog_input_goals").dialog({
		autoOpen: false,
		modal: true,
		buttons: [{"text": "확인", "click": function(){
			applyGoals($("#dialog_input_goal_random").prop("checked"));
			$(this).dialog("close");
		}}]		
	});
	
	if("${isLeader }" == "true"){
		$(".btn_leader").show();	
	}else{
		$(".btn_leader").hide();
	}
		
	$("#btn_draw").click(function(){
		makeModel();
		drawModel();
	});
	
	$("#btn_accept").click(acceptPaper);
	
	//GO ALL 버튼 이벤트
	$( "#btn_go" ).click(function(){
			
		// 루프 돌며 모두 GO
		for(var i = 0; i < num; i++){		
			go(i);		
		}
			
	});
	
	$("#btn_back").click(function(){
		window.location = "../../note";
	});
	
	drawLine();
	updateOrder();
	updateGoals();
	drawModel();
	updateStatus();
	
	if(status == "0"){
		$("#dialog_input_goals").dialog("open");
	}else{
		timer["status"] = window.setInterval(updateStatus, 2000);	
	}
	
	if(status == "1"){
		timer["order"] = window.setInterval(updateOrder, 1000);
	}
	
	
});

function applyGoals(randomGoal){
	
	for(var i = 0; i < num; i++){		
		$("#input_goal_" + i).val($("#dialog_input_goal_" + i).val());		
	}
	
	if(randomGoal){
		
		for(var i = 0; i < num; i++){
			var n = Math.floor((Math.random() * num));
			//var m = Math.floor((Math.random() * num));
			
			var temp = $("#input_goal_" + i).val();
			$("#input_goal_" + i).val($("#input_goal_" + n).val());
			$("#input_goal_" + n).val(temp);
			
		}
		
	}
	
	//입력된 결과 값 저장
	for(var i = 0; i < num; i++){
		
		if($("#input_goal_"+i).val()){
			$.post(paperId + "/goals", {"order": i, "goalName": $("#input_goal_" + i).val() } , function(data){
				if(data != true){
					alert("Update Goal Fail :" + i);
				}
			});	
		}
	}
	
	//오픈 상태로 변환
	changeStatus(1);
	updateStatus();
	timer["order"] = window.setInterval(updateOrder, 1000);
	
	
}

function updateGoals(){
	
	$.get(paperId + "/goals", function(data){
		if(data.length){
			for(var i = 0; i < data.length; i++){
				if(data[i]){
					$("#input_goal_"+i).val(data[i].name);	
				}
			}
		}
	});	
}

function acceptPaper(){
	if(model){
		changeStatus(2);
	} else {
		alert("사다리부터 그리시지..");
	}
}

function makeModel(){
	$.post(paperId + "/model/" + line + "/" + num, function(data){
		if(data == true){
			drawModel();	
		}else{
			alert("사다리 생성 실패 ㅠㅠ");
		}
	});
}

function drawModel(){

	$.get(paperId + "/model", function(data){
		model = data;

		// 생성된 사다리 모델(board) 기반으로 사다리 그리기
		for(var i = 0; i < model.length; i++){
			for(var j = 0; j < model[i].length; j++){
				
				if(j == model[i].length - 1){
					if(model[i][j] == 1){
						$("#sadari_"+(i)+"_"+(j)).css({"background-image": "url('../../images/10.png')"});
					}else{
						$("#sadari_"+(i)+"_"+(j)).css({"background-image": "url('../../images/00.png')"});
					}
					continue;
				}
				
				if(model[i][j] == 0 && model[i][j+1] == 1){
					$("#sadari_"+(i)+"_"+(j)).css({"background-image": "url('../../images/01.png')"});
				}else if(model[i][j] == 1 && model[i][j+1] == 0){
					$("#sadari_"+(i)+"_"+(j)).css({"background-image": "url('../../images/10.png')"});
				}else{
					$("#sadari_"+(i)+"_"+(j)).css({"background-image": "url('../../images/00.png')"});
				}
			}
		}
	});	
}

function updateStatus(){
	
	$.get(paperId + "/status", function(data){
		status = data;		
	});	
	
	$("#paper_status").text(status_text[status]);		
	
	switch (status) {
	case "0":
		
		$("#btn_open").prop("disabled", false);
		$("#btn_draw").prop("disabled", true);
		$("#btn_accept").prop("disabled", true);
		$("#btn_go").prop("disabled", true);
		//$(".input_goal").prop("disabled", false);
		$(".btn_assign").prop("disabled", false);
		
		break;

	case "1":
		
		//drawModel();
		
		$("#btn_open").prop("disabled", true);
		$("#btn_draw").prop("disabled", false);
		if(model){
			$("#btn_accept").prop("disabled", false);
			
		} else {
			$("#btn_accept").prop("disabled", true);			
		}
		
		$("#btn_go").prop("disabled", true);
		//$(".input_goal").prop("disabled", true);
		$(".btn_assign").prop("disabled", false);
		
		break;

	case "2":
	
		drawModel();
		
		$("#btn_open").prop("disabled", true);
		$("#btn_draw").prop("disabled", true);
		$("#btn_accept").prop("disabled", true);
		$("#btn_go").prop("disabled", false);
		//$(".input_goal").prop("disabled", true);
		$(".btn_assign").prop("disabled", true);
		
		window.clearInterval(timer["status"]);
		
		break;

	case "3":

		drawModel();
		
		$("#btn_open").prop("disabled", true);
		$("#btn_draw").prop("disabled", true);
		$("#btn_accept").prop("disabled", true);
		$("#btn_go").prop("disabled", false);
		//$(".input_goal").prop("disabled", true);
		$(".btn_assign").prop("disabled", true);
		
		window.clearInterval(timer["status"]);
		
		break;

		
	}
	
	
}

function changeStatus(s){
	$.post(paperId + "/status", { "status": s }, function(data){
		if(data){
			updateStatus();
		} else {
			alert("Fail Change Status");
		}	
	});
}

function updateOrder(){
	
	$.get(paperId + "/order", function(data){
		var max = true;
		for(var i = 0; i < num; i++){
			if(data[i]){
				$("#ch_"+i+" > img").attr("src", "../../images/ch_"+data[i].character+".png");
				$("#ch_"+i+" > span").empty().append(data[i].name);
				$("#ch_"+i+" > span").fadeIn();				
			} else{
				max = false;
			}
		}			
		
		if(status != "1"){
			clearInterval(timer["order"]);
		}
		
		if(max){
			clearInterval(timer["order"]);
		}		
	});	
}

function sendOrder(num){
	
	$.post(paperId + "/${sadari_user.id}/"+num, function(data){
		if(data == true){
			refreshOrder();
		}else{
			alert("거긴.. 아니되요..");
		}
	});
	
}

//세로선 그리기
function drawLine(){
	
	// 사다리 그릴 테이블 초기화
	$("#sadari").empty();

	
	// 세로 선 그리기	
	for(var i = 0; i < line; i++){
		$("#sadari").append("<tr id='sadari_"+(i)+"'></tr>");
		
		for(var j = 0; j < num; j++){
			$("#sadari_" + i).append("<td class='cell' id='sadari_" + i + "_" + j + "'></td>");
		}		
	}
	
	// 결과 입력
	$("#sadari").append("<tr id='sadari_goals' height='100'></tr>");
	for(var i = 0; i < num; i++){
		$("#sadari_goals").append("<td align='center'><input class='input_goal' id='input_goal_"+i+"' size='10' disabled='disabled'></td>");
	}
	
	// 참가 인원에 대한 각종 처리
	for(var i = 0; i < num; i++){
		
		// 캐릭터 DIV 추가
		$("body").append("<div id='ch_"+i+"' class='ch' align='center'><span class='label_name' id='name_"+i+"'>???</span><img src='../../images/qq.png' height='100' onClick='assign("+i+")'></div>");
		$("body").append("<div id='boom_"+i+"' class='boom' align='center'><img src='../../images/bb.png' height='80'></div>");
		// 캐릭터 위치 초기화
		move("#ch_"+i, 0, i);
	}
}

function assign(num){
	
	if(status == "1"){
		sendOrder(num);	
	}
	
}

//사다리 가로 축 위치정보
function getX(line, num){
	return $("#sadari_"+line+"_"+num).position().left;	
}

//사다리 세로 축 위치정보
function getY(line, num){
	return $("#sadari_"+line+"_"+num).position().top;	
}

// 캐릭터 이동(캐릭터 번호, 사다리 세로, 사다리 가로)
function move(select, line, num, isPuff){
	
	var top = $(select).position().top;
	var left = $(select).position().left;

	
	$(select).animate({ "left": getX(line, num)+"px", "top": getY(line, num)+"px" }, "fast");
	
	return $(select); 
}

//개별 캐릭터 사다리 진행
function go(n){

	
	
	if(isOneGoal){
		for(var i = 0; i < num; i++){
			if(i != realGoalNumber){
				move("#boom_"+i, boomLine, i).delay(1000).show("slide");				
			}
		}
	}
	
	var index = n;

	// 캐릭터 위치 초기화
	move("#ch_"+n, 0, n).show();
	
	
	
	for(var i = 0; i < line; i++){
		
		if(model[i][index] != 0) {
			index--;			
			move("#ch_"+n, i-1, index);
		}else{
			if(index+1 < num){
				if(model[i][index+1] != 0) {
					index++;
					move("#ch_"+n, i-1, index);
				}
			}
		}
		move("#ch_"+n, i, index);
	
		if(isOneGoal){
			if(i == boomLine){
				if(index != realGoalNumber){
					$("#ch_"+n).effect("shake", {distance: "20", times: "5"}).hide("puff", {percent: "300" }, "slow");		
				}
			}
		}
		
		
	}
}

</script>

</body>
</html>